package org.microdream.easy.deploy.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import ice.server.comm.BaseServiceImpl;
import ice.server.comm.CommRepository;
import ice.server.comm.ParamBulider;
import org.microdream.easy.deploy.dao.DMenuRepository;
import org.microdream.easy.deploy.po.DMenu;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DMenuService extends BaseServiceImpl<DMenu, Integer>{

    @Resource
    private DMenuRepository dMenuRepository;

    @Override
    public CommRepository<DMenu, Integer> getRepository() {

        return dMenuRepository;
    }

    @Override
    public Integer getIdenty(DMenu t) {
        return t.getId();
    }


    public JSONArray getMenuTree() {
        List<DMenu> dMenus = this.find(ParamBulider.build().addEqual("isShow",0).get());
        return build("0",dMenus,"nodes");
    }

    private JSONArray build(String fcode,List<DMenu> dMenus, String childrenKey){
        JSONArray jsonArray = new JSONArray();
        dMenus.stream().forEach(dMenu -> {
            if(dMenu.getMenuFCode().equals(fcode)){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id",dMenu.getId());
                jsonObject.put("text",dMenu.getMenuName());
                jsonObject.put("icon",dMenu.getMenuImage());
                jsonObject.put("url",dMenu.getMenuUrl());
                jsonObject.put("code",dMenu.getMenuCode());
                JSONArray ja = build(dMenu.getMenuCode(),dMenus, childrenKey);
                if(!ja.isEmpty()) {
                    jsonObject.put(childrenKey, ja);
                }
                jsonArray.add(jsonObject);
            }
        });
        return jsonArray;
    }
}
